import React, { Component, createRef } from 'react'
import styles from "./index.module.css"
import PropsType from "prop-types"
class Sticky extends Component {

    placeholder = createRef()
    content = createRef()
    handleScroll = () => {
        const { height } = this.props
        console.log('scroll')
        const placeholderEL = this.placeholder.current
        const contentEL = this.content.current
        const { top } = placeholderEL.getBoundingClientRect()
        // console.log(top)
        if (top < 0) {
            // 吸顶
            contentEL.classList.add(styles.fixed)
            placeholderEL.style.height = `${height}px`
        } else {
            // 不吸
            contentEL.classList.remove(styles.fixed)
            placeholderEL.style.height = '0px'
        }
    }
    componentDidMount() {
        window.addEventListener('scroll', this.handleScroll)
    }
    componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll)
    }
    render() {
        return (
            <div>
                {/* 占位 */}
                <div ref={this.placeholder}></div>
                <div ref={this.content}>
                    {/* 内容 */}
                    {this.props.children}
                </div>
            </div>
        )
    }
}
Sticky.PropsType = {
    heigth: PropsType.number.isRequired
}
export default Sticky